'use strict';

let fs = require('fs');
let path = require('path');
let router = require('koa-router')();

function filterControllers() {
    let files = fs.readdirSync(__dirname);

    let filterFile = files.filter(fileName => {
        return fileName.endsWith('.js') && fileName !== 'index.js';
    });

    return filterFile;
};


function registeRoute(files) {
    files.forEach(item => {
        let fullPath = path.join(__dirname, item);

        let fileRoute = require(fullPath);

        for (let requestaddress in fileRoute) {
            let type = fileRoute[requestaddress][0];

            let address_fn = fileRoute[requestaddress][1];

            if (type === 'get') {
                router.get(requestaddress, address_fn);
            } else if (type === 'post') {
                router.post(requestaddress, address_fn);
            } else if (type === 'put') {
                router.put(requestaddress, address_fn);
            } else if (type === 'delete') {
                router.delete(requestaddress, address_fn);
            } else {
                console.log('请求的类型错误，请确认后重试!');
            }
        }
    });
};

module.exports = function () {
    let everyFile = filterControllers();

    registeRoute(everyFile);

    return router.routes();
};